﻿using MqLibrary;
using RabbitMqService.Workers;
using RabbitMqService.Workers.SendMail;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Script.Serialization;

namespace RabbitMqService.Worker
{
    public class SendMailWorker : IWorker
    {
        static SendMailWorker()
        {
            IDictionary dict = ConfigurationManager.GetSection("SendMail") as IDictionary;
            //THREADNUMBER = Convert.ToInt32(dict["THREADNUMBER"]);
            TEMPLATEMAIL = dict["TEMPLATEMAIL"].ToString();
            APIUSER = dict["APIUSER"].ToString();
            APIKEY = dict["APIKEY"].ToString();
            FROM = dict["FROM"].ToString();
            SUBJECT = dict["SUBJECT"].ToString();
            FORMNAME = dict["FORMNAME"].ToString();
        }
        ////并发发送数量
        //private static readonly int THREADNUMBER;
        //模板名称
        private static readonly string TEMPLATEMAIL;
        //用户标示
        private static readonly string APIUSER;
        private static readonly string APIKEY;
        //发信域名
        private static readonly string FROM;
        //"mmJLRsWUuf9xuwhk2f2ZpLQWsyUKFEem.sendcloud.org";
        //邮件主题
        private static readonly string SUBJECT;
        private static readonly string FORMNAME;


        public void DoWork(object o)
        {
            RabbitHelper<EmailModel> cs = new RabbitHelper<EmailModel>();
            JavaScriptSerializer js = new JavaScriptSerializer();
            bool RabbitIsNull = false;
          
            while (true)
            {
               
                if (RabbitIsNull)
                {
                    Thread.Sleep(5000);
                }
                EmailModel result = cs.GetRabbitMq(RabbitTypeEnum.Email);
                if (result == null)
                {
                    RabbitIsNull = true;
                    continue;
                }
                Task<string> t = Send(result);
                //发送失败的时候执行
                t.ContinueWith((task, r) =>
                {

                    if (task.Exception != null)
                    {
                        Log.WriteMailInfo("to" + r + "  发送失败  " + task.Exception.InnerException.Message);
                    }
                }, result.SendAddress, TaskContinuationOptions.OnlyOnFaulted);
                //发送成功的时候执行
                t.ContinueWith((task, r) =>
                {
                    var returnJson = js.Deserialize<ReturnJson>(task.Result);
                    //转发失败
                    if (returnJson != null && returnJson.Result == false)
                    {
                        Log.WriteMailInfo("to" + r + "  发送失败  " + returnJson.StatusCode + "  " + returnJson.Message);
                    }
                    else if (returnJson == null)
                    {
                        Log.WriteMailInfo("to" + r + "  发送失败   在json反序列化是出现问题");
                    }
                    //转发成功
                    else Log.WriteMailInfo("to" + r + "  发送成功");

                },
                result.SendAddress, TaskContinuationOptions.OnlyOnRanToCompletion);
                //发送取消是执行
                t.ContinueWith((task, r) =>
                {
                    Log.WriteMailInfo("to" + r + "  发送取消");
                }
                , result.SendAddress, TaskContinuationOptions.OnlyOnCanceled);

                //List<EmailModel> emailList = new List<EmailModel>();
                ////取一定数量的email信息
                //for (int i = 0; i < THREADNUMBER; i++)
                //{
                //    //inRabbit();
                //    EmailModel result = cs.GetRabbitMq(RabbitTypeEnum.Email);
                //    if (result != null)
                //    {
                //        RabbitIsNull = false;
                //        emailList.Add(result);
                //    }
                //    else
                //    {
                //        RabbitIsNull = true;
                //        break;
                //    }
                //}
                ////x++;
                ////DebugWriter.Writer(x.ToString());
                ////Thread.Sleep(1000);

                //if (emailList.Count != 0)
                //{
                //    //初始化一个大小等于取的返回邮件个数的任务数组
                //    Task<string>[] taskArr = new Task<string>[emailList.Count];
                //    //创建一定数量的任务并运行
                //    int n = 0;
                //    foreach (var emailModel in emailList)
                //    {
                //        taskArr[n] = Task.Run(() => Send(emailModel));
                //        n++;
                //    }
                //    foreach (var task in taskArr)
                //    {
                //        try
                //        {
                //            var result = task.Result;
                //            var returnJson = js.Deserialize<ReturnJson>(result);
                //            if (result != null && returnJson.Result == false)
                //            {
                //                throw new ConfigException { Source = "调用邮件接口返回数据有问题", ReturnJsonString = js.Serialize(returnJson), ReturnJson = returnJson };
                //            }
                //        }
                //        catch (AggregateException e)
                //        {
                //        }
                //    }
                //}
            }
        }
        /// <summary>
        /// 发送带有模板的邮件
        /// </summary>
        private async Task<string> Send(EmailModel emailbody)
        {

            //邮件发送模板的api地址
            String url = "http://api.sendcloud.net/apiv2/mail/sendtemplate";
            // 初始化Xsmtpapi类型      
            var emailBody = new Sub { EmailBody = new List<string> { emailbody.EmailBody } };
            var to = new List<string> { emailbody.SendAddress };
            var xsmtpapi = new Xsmtpapi { sub = emailBody, to = to, };
            //声明个json序列化辅助类
            JavaScriptSerializer js = new JavaScriptSerializer();
            //进行序列化  对要替换的内容 进行添加%%处理
            var xsmtpapiJson = js.Serialize(xsmtpapi).Replace("EmailBody", "%EmailBody%");
            //开始构架发送代码          
            HttpResponseMessage response = null;
            using (HttpClient client = new HttpClient())
            {
                List<KeyValuePair<String, String>> paramList = new List<KeyValuePair<String, String>>();
                paramList.Add(new KeyValuePair<string, string>("apiUser", APIUSER));
                paramList.Add(new KeyValuePair<string, string>("apiKey", APIKEY));
                paramList.Add(new KeyValuePair<string, string>("from", FROM));
                paramList.Add(new KeyValuePair<string, string>("fromName", FORMNAME));
                paramList.Add(new KeyValuePair<string, string>("subject", emailbody.EmailTitle));
                paramList.Add(new KeyValuePair<string, string>("xsmtpapi", xsmtpapiJson));
                paramList.Add(new KeyValuePair<string, string>("templateInvokeName", TEMPLATEMAIL));
                response = await client.PostAsync(url, new FormUrlEncodedContent(paramList));
                var result = await response.Content.ReadAsStringAsync();
                return result;
            }
        }



        /// <summary>
        /// 测试的用于向Rabbit里面插入数据
        /// </summary>
        private void inRabbit()
        {
            RabbitHelper<EmailModel> cs = new RabbitHelper<EmailModel>();
            EmailModel em = new EmailModel();
            em.FromAddress = "changjianguo@163.com";
            em.SendAddress = "528957877@qq.com";
            em.EmailTitle = "逗你玩";
            em.EmailBody = "恭喜你成为亿万富翁";
            em.EmailType = ModelType.Notice;
            cs.InsertRabbitMq(RabbitTypeEnum.Email, em);
        }
    }












}
